<template>
  <div class="TabsSteps">
    <div class="TabsSteps-container">
      <div class="TabsSteps-container-steps">
        <el-steps
          :active="state.activeIndex - 0"
          finish-status="success"
          simple
        >
          <el-step
            v-for="(item, index) in state.stepParams"
            :status="item.status"
            :title="item.title"
            @click.native="handleStep(index)"
          />
        </el-steps>
      </div>
      <div class="TabsSteps-container-tabs">
        <el-tabs
          :tab-position="'left'"
          v-model="state.active"
          style="height: 400px"
          @tab-click="handleTabStep"
        >
          <el-tab-pane label="基本信息" name="0" disabled="true">
            <el-form
              ref="formRef"
              @keyup.enter="baTable.onSubmit(formRef)"
              :model="baTable.form.items"
              label-position="left"
              :label-width="baTable.form.labelWidth + 'px'"
              :rules="rules"
              v-if="!baTable.form.loading"
            >
              <div class="baseInfo">
                <el-form-item label="计划名称" prop="planName">
                  <el-input
                    v-model="baTable.form.items!.planName"
                    placeholder="请输入计划名称"
                  />
                </el-form-item>
                <el-form-item label="执行时间" prop="endTime">
                  <el-date-picker
                    v-model="state.doTime"
                    type="datetimerange"
                    start-placeholder="开始时间"
                    end-placeholder="截止时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    @change="getValue"
                  />
                </el-form-item>
                <el-form-item label="循环周期" prop="cycle">
                  <el-input
                    v-model="baTable.form.items!.cycle"
                    placeholder="请输入循环周期"
                  >
                    <template #append>
                      <el-select
                        v-model="baTable.form.items!.unit"
                        placeholder="单位"
                        style="width: 80px"
                        @change="getUnit"
                      >
                        <el-option
                          v-for="(item, index) in state.unit"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item label="提前通知时间(分钟)" prop="reminderTime">
                  <el-input-number
                    v-model="baTable.form.items!.reminderTime"
                    controls-position="right"
                    :min="0"
                  />
                </el-form-item>
                <el-form-item label="停用时间" prop="stopTime">
                  <el-date-picker
                    v-model="baTable.form.items!.stopTime"
                    type="date"
                    placeholder="请选择停用时间"
                    format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD"
                  />
                  <div class="block-help">
                    到停用时间本计划将不再循环，若长期使用该计划，停用时间可为空
                  </div>
                </el-form-item>
                <FormItem
                  label="计划状态"
                  v-model="baTable.form.items!.status"
                  type="radio"
                  prop="status"
                  :data="{
                    content: { 0: '停用', 1: '启用' },
                    childrenAttr: { border: true },
                  }"
                />
                <el-form-item label="巡检人员" prop="employeeName">
                  <el-select
                    v-model="baTable.form.items!.employeeName"
                    placeholder="请选择巡检人员"
                    @change="changeEmployee"
                  >
                    <el-option
                      v-for="item in state.employeeOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item"
                      :disabled="item.status == 1"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="巡检内容" name="1" disabled="true">
            <div></div>
          </el-tab-pane>
          <el-tab-pane label="高级设置" name="2" disabled="true"
            ><div></div
          ></el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, inject } from "vue";
import type baTableClass from "@/utils/baTable";
import type { ElForm, FormRules, ElTree, FormInstance } from "element-plus";
import { treePerson } from "@/utils/common";
import { ElNotification } from "element-plus"; //处理导航信息
import { stat } from "fs";
import { promises } from "dns";
import { fa } from "element-plus/es/locale";

const baTable = inject("baTable") as baTableClass;
const formRef = ref<InstanceType<typeof ElForm>>();
const staff = inject("staff") as any;

const state: {
  activeIndex: number;
  active: string | number;
  stepParams: any[];
  stepSuc: any[];
  employeeOptions: anyObj[];
  doTime: any[];
  unit: any[];
  cycleTime: number;
} = reactive({
  activeIndex: 0, //步骤条默认为选择设备
  active: "0", //默认为选择设备页面
  stepSuc: [0], // 已选步骤
  stepParams: [
    // 步骤参数
    {
      title: "基本信息",
      name: "0",
      status: "process",
    },
    {
      title: "巡检内容",
      name: "1",
      status: "wait",
    },
    {
      title: "高级设置",
      name: "2",
      status: "wait",
    },
  ],
  doTime: [],
  employeeOptions: [], //维护服务人员列表
  unit: [
    { label: "时", value: "hour" },
    { label: "天", value: "day" },
    { label: "周", value: "week" },
    { label: "月", value: "month" },
    { label: "季", value: "quarter" },
    { label: "年", value: "year" },
  ], //单位
  cycleTime: 0, //用来与执行时间比对
});

// 点击tab
const handleTabStep = (pane: any) => {
  console.log("点击tab", pane);

  state.stepSuc = []; //清空已选步骤
  state.activeIndex = parseInt(pane.props.name);
  let temp = state.activeIndex;
  while (temp !== 0) {
    state.stepSuc.push(--temp);
  }
  handleStatus();
};

// const beforeLeave = async (activeName: any, oldActiveName: any) => {
//   console.log("activeName", activeName, "oldActiveName", oldActiveName);
//   return await beforeLeaveResult(oldActiveName);
// };

// const beforeLeaveResult = (index: any) => {
//   return Promise.all(getValidateField(index + ""))
//     .then((res: any) => {
//       state.activeIndex += 1;
//       state.active = state.activeIndex + "";
//       handleStatus();
//       return true;
//     })
//     .catch((err: any) => {
//       console.log("err", err);
//       return false;
//     });
// };

// 点击步骤条
const handleStep = (val: any) => {
  console.log("点击步骤条", val);
  // if (state.stepSuc.includes(val)) {
  //   state.activeIndex = val;
  //   state.active = val.toString();
  // }
  // handleStatus();
};
//步骤条样式修改
const handleStatus = () => {
  switch (state.activeIndex) {
    case 0:
      state.stepParams[0].status = "process";
      state.stepParams[1].status = "wait";
      state.stepParams[2].status = "wait";
      break;
    case 1:
      state.stepParams[0].status = "finish";
      state.stepParams[1].status = "process";
      state.stepParams[2].status = "wait";
      break;
    case 2:
      state.stepParams[0].status = "success";
      state.stepParams[1].status = "finish";
      state.stepParams[2].status = "process";
      break;
    default:
      state.stepParams[0].status = "process";
      state.stepParams[1].status = "wait";
      state.stepParams[2].status = "wait";
      break;
  }
};
//上一步
const handleLastStep = () => {
  console.log("上一步当前index", state.activeIndex);
  if (state.activeIndex !== 0) {
    state.activeIndex -= 1;
    state.active = state.activeIndex + "";
    handleStatus();
  } else {
    ElNotification({
      type: "warning",
      message: "当前已是第一步",
    });
  }
};
//下一步
const handleNextStep = () => {
  console.log("下一步当前index", state.activeIndex);
  if (state.activeIndex !== 2) {
    Promise.all(getValidateField(state.activeIndex + ""))
      .then((res: any) => {
        state.activeIndex += 1;
        state.active = state.activeIndex + "";
        handleStatus();
      })
      .catch((err: any) => {
        console.log("err", err);
      });
  } else {
    ElNotification({
      type: "warning",
      message: "当前已是最后一步，请直接点击确定发布巡检计划",
    });
  }
};
//下一步之前触发校验规则
const getValidateField = (index: string): any => {
  console.log("下一步之前触发校验规则", index);
  let promises: any[] = [];
  switch (index) {
    case "0":
      let fields = [
        "planName",
        "endTime",
        "cycle",
        "reminderTime",
        "status",
        "employeeName",
      ];
      for (let i = 0; i < fields.length; i++) {
        promises.push(formRef.value?.validateField(fields[i]));
      }
      return promises;
    case "1":
      return promises;
  }
};

//执行时间
const getValue = (value: any) => {
  console.log("执行时间", value);
  if (value) {
    baTable.form.items!.startTime = value[0];
    baTable.form.items!.endTime = value[1];
  } else {
    baTable.form.items!.startTime = "";
    baTable.form.items!.endTime = "";
  }
  // baTable.comSearch.form = Object.assign(
  //   baTable.comSearch.form,
  //   value
  //     ? {
  //         startTime: value[0],
  //         endTime: value[1],
  //       }
  //     : { startTime: "", endTime: "" }
  // );
};

//选择单位 单位为天以上都放行
const getUnit = (val: any) => {
  console.log("选择单位", val);
  if (!state.doTime.length) {
    ElNotification({
      type: "warning",
      message: "执行时间必填",
    });
  } else {
    let firstDate = new Date(state.doTime[0]).getTime();
    let lastDate = new Date(state.doTime[1]).getTime();
    switch (val) {
      case "hour":
        if (lastDate - firstDate < baTable.form.items!.cycle * 3600000) {
          formRef.value?.validateField("cycle");
        } else {
          ElNotification({
            type: "warning",
            message:
              "可执行时间范围超过循环周期，请重新选择巡检执行时间或循环周期",
          });
        }
        break;
      case "day":
        console.log(
          "选择单位",
          lastDate - firstDate,
          lastDate - firstDate < baTable.form.items!.cycle * 86400000
        );
        if (lastDate - firstDate < baTable.form.items!.cycle * 86400000) {
          formRef.value?.validateField("cycle");
        } else {
          ElNotification({
            type: "warning",
            message:
              "可执行时间范围超过循环周期，请重新选择巡检执行时间或循环周期",
          });
        }
        break;
      default:
        formRef.value?.validateField("cycle"); //单独触发某个字段验证规则
        break;
    }
  }
};

//获取维护服务巡检人员
const getEmployee = () => {
  staff
    .getSingleAndListStaffAuto({ pageNum: 1, pageSize: 1000 })
    .then((res: any) => {
      console.log("售后人员", res);
      state.employeeOptions = treePerson(res.rows, "name", "name");
    });
};

type Employee = {
  id: number;
  name: string;
  value: string;
};
//选择巡检人员
const changeEmployee = (e: Employee) => {
  console.log("选择售后人员", e);
  baTable.form.items!.employeeName = e.name; //分配售后人员名称
  baTable.form.items!.employeeId = e.id; //分配售后人员id
};

const rules = reactive<FormRules>({
  planName: [{ required: true, message: "计划名称不能为空", trigger: "blur" }],
  endTime: [{ required: true, message: "执行时间不能为空", trigger: "blur" }],
  cycle: [
    { required: true, message: "循环周期不能为空", trigger: "blur" },
    {
      validator: function (rule, value, callback) {
        console.log("循环周期校验", value, rule, state.doTime);
        let firstDate = new Date(state.doTime[0]).getTime();
        let lastDate = new Date(state.doTime[1]).getTime();
        switch (baTable.form.items!.unit) {
          case "hour":
            state.cycleTime = value * 3600000;
            if (lastDate - firstDate < state.cycleTime) {
              callback();
            } else {
              callback(
                new Error(
                  "可执行时间范围超过循环周期，请重新选择巡检执行时间或循环周期"
                )
              );
            }
            break;
          case "day":
            console.log("day", lastDate - firstDate);
            state.cycleTime = value * 86400000;
            if (lastDate - firstDate < state.cycleTime) {
              callback();
            } else {
              callback(
                new Error(
                  "可执行时间范围超过循环周期，请重新选择巡检执行时间或循环周期"
                )
              );
            }
            break;
          default:
            callback();
            break;
        }
      },
      trigger: "blur",
    },
  ],
  status: [{ required: true, message: "计划状态不能为空", trigger: "change" }],
  employeeName: [
    { required: true, message: "巡检人员不能为空", trigger: "change" },
  ],
  reminderTime: [
    { required: true, message: "提前通知时间不能为空", trigger: "blur" },
  ],
});

onMounted(() => {
  getEmployee();
  baTable.form.items!.unit = "hour";
});
defineExpose({ handleLastStep, handleNextStep });
</script>
<style lang="scss" scoped>
.baseInfo {
  margin-top: 10px;
}
.el-tabs__header .is-left {
  opacity: 0;
}
</style>
